'use strict';

const Controller = require('egg').Controller;
const mockjs = require('mockjs');

let USER_IDENTITY = 5;

const Users = mockjs.mock({
  [`record|${USER_IDENTITY++}`]: [
    {
      id: '@id',
      name: '@cname',
      age: '@natural(20, 45)',
    },
  ],
}).record;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'Hello egg!';
  }

  get dataSubscribeService() {
    return this.ctx.service.dataSubscribeService;
  }

  async users() {
    const connectionId = this.ctx.request.query.connectionId;
    if (!connectionId) {
      return;
    }
    this.dataSubscribeService.subscribe({
      name: 'User',
      id: Users.map((user) => user.id),
      connectionId,
    });
    this.ctx.body = Users;
  }

  async updateUser() {
    const connectionId = this.ctx.request.query.connectionId;
    if (!connectionId) {
      return;
    }
    const userData = this.ctx.request.body;
    if (!userData) {
      return;
    }
    const userId = this.ctx.params.userId && this.ctx.params.userId !== '0' || ++USER_IDENTITY;
    const user =
      Users.find((u) => {
        return u.id === userId;
      }) || userData;
    if (!user.id) {
      user.id = userId;
      this.dataSubscribeService.subscribe({
        name: 'User',
        id: userId,
        connectionId
      });
    } else {
      Object.assign(user, userData);
    }
    this.dataSubscribeService.publish({
      name: 'User',
      id: user.id,
      data: user,
    });
    this.ctx.body = userData;
  }

  async userBooks() {
    const { userId } = this.ctx.params;
    if (!userId) {
      return;
    }
    const connectionId = this.ctx.request.query.connectionId;
    if (!connectionId) {
      return;
    }
    const user = Users.find((user) => {
      return user.id === userId;
    });
    if (!user) {
      return;
    }
    try {
      if (!user.books) {
        user.books = mockjs.mock({
          'record|10': [
            {
              id: '@id',
              name: '@ctitle',
            },
          ],
        }).record;
      }
      this.dataSubscribeService.subscribe({
        name: 'Book',
        id: user.books.map((book) => book.id),
        connectionId,
      });
      this.ctx.body = user.books;
    } catch (err) {
      this.ctx.logger.error(err.message);
    }
  }

  async updateBook() {
    const { userId, bookId } = this.ctx.params;
    const bookData = this.ctx.request.body;
    if (!bookData || !userId) {
      return;
    }
    const connectionId = this.ctx.request.query.connectionId;
    if (!connectionId) {
      return;
    }
    const user = Users.find((u) => {
      return u.id === userId;
    });
    if (!user) {
      return;
    }
    const book = bookId && bookId !== '0' ? user.books.find((b) => {
      return b.id === bookId;
    }) : bookData;
    if (!book.id) {
      book.id = user.books.length + 1;
      this.dataSubscribeService.subscribe({
        name: 'Book',
        id: book.id,
        connectionId
      });
    } else {
      Object.assign(book, bookData);
    }
    this.dataSubscribeService.publish({
      name: 'Book',
      id: book.id,
      data: book,
    });
    this.ctx.body = bookData;
  }

  async test() {
    const data = this.ctx.request.body;
  }
}

module.exports = HomeController;
